package com.cskaoyan.service.admin;

import com.cskaoyan.bean.MarketIssue;
import com.cskaoyan.bean.MarketIssueExample;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.mapper.MarketIssueMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author klw
 * @Data 2022/11/20 下午10:43
 */

@Service
public class IssueServiceImpl implements IssueService{

    @Autowired
    MarketIssueMapper marketIssueMapper;


    @Override
    public CommonData<MarketIssue> query(String question, BasePageInfo info) {
        PageHelper.startPage(info.getPage(), info.getLimit());
        MarketIssueExample marketIssueExample = new MarketIssueExample();
        marketIssueExample.setDistinct(true);
        MarketIssueExample.Criteria criteria = marketIssueExample.createCriteria();

        if(question != null && !"".equals(question)){
            criteria.andQuestionLike("%" + question + "%");
        }

        criteria.andDeletedEqualTo(false);

        marketIssueExample.setOrderByClause(info.getSort() + " " + info.getOrder());
        List<MarketIssue> marketIssues = marketIssueMapper.selectByExample(marketIssueExample);
        PageInfo pageInfo = new PageInfo(marketIssues);

        return CommonData.data(pageInfo);
    }

    @Override
    @Transactional
    public void delete(MarketIssue marketIssue) {
        Integer id = marketIssue.getId();
        marketIssueMapper.deleteById(id);
    }

    @Override
    public MarketIssue createIssue(MarketIssue marketIssue) {
        String question = marketIssue.getQuestion();
        int res = marketIssueMapper.selectByQuestion(question);
        if(res != 0){
            return null;
        }
        marketIssue.setAddTime(new Date());
        marketIssue.setUpdateTime(new Date());
        marketIssue.setDeleted(false);

        marketIssueMapper.insert(marketIssue);
        return marketIssue;
    }

    @Override
    public MarketIssue updateIssue(MarketIssue marketIssue) {
        marketIssue.setUpdateTime(new Date());

        marketIssueMapper.updateByPrimaryKeySelective(marketIssue);

        return marketIssue;
    }
}
